package com.ysweet.web.core.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ysweet.common.constant.ShopConstants;
import com.ysweet.common.core.redis.RedisCache;
import com.ysweet.common.exception.BaseException;
import com.ysweet.shop.domain.YsUser;
import com.ysweet.shop.domain.dto.LoginParam;
import com.ysweet.shop.service.IYsUserService;
import com.ysweet.web.core.config.WxMaConfiguration;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName 登陆认证服务类
 * @Author 小金木
 * @Date 2021年6月11日08:56:14
 **/
@Slf4j
@Service
@RequiredArgsConstructor()
public class AuthService {

	private final IYsUserService userService;
	private final RedisCache redisCache;
	private static Integer expiredTimeIn;

	@Value("${token.token-expired-in}")
	public void setExpiredTimeIn(Integer expiredTimeIn) {
		AuthService.expiredTimeIn = expiredTimeIn;
	}

	/**
	 * 小程序登陆
	 *
	 * @param loginParam loginParam
	 * @return long
	 */
	@Transactional(rollbackFor = Exception.class)
	public YsUser wxappLogin(LoginParam loginParam) {
		String code = loginParam.getCode();
		try {
			//读取redis配置
			WxMaService wxMaService = WxMaConfiguration.getWxMaService();
			WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
			String openid = session.getOpenid();
			//如果开启了UnionId
			if (StrUtil.isNotBlank(session.getUnionid())) {
				openid = session.getUnionid();
			}
			YsUser ysUser = userService.getOne(Wrappers.<YsUser>lambdaQuery()
				.eq(YsUser::getOpenid, openid), false);
			if (ObjectUtil.isNull(ysUser)) {
				ysUser = YsUser.builder()
					.openid(openid)
					.build();
				userService.save(ysUser);
			}
			//redisCache.setCacheObject(ShopConstants.MINI_SESSION_KET + ysUser.getId(), session.getSessionKey());
			return ysUser;
		} catch (WxErrorException e) {
			e.printStackTrace();
			log.error(e.getMessage());
			throw new BaseException(e.toString());
		}

	}

    /***
     * 保存token到redis
	 * @param token
     * @param yxUser
	 */
	public void saveToken(String token, YsUser yxUser) {
		redisCache.setCacheObject(ShopConstants.APP_LOGIN_USER + yxUser.getId(), yxUser, AuthService.expiredTimeIn, TimeUnit.SECONDS);
	}

	/**
	 * 退出登录
	 *
	 * @param token /
	 */
	public void logout(String uid, String token) {
		String key = ShopConstants.APP_LOGIN_USER + uid + ":" + token;
		redisCache.deleteObject(key);
	}


}
